import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    status: false,
    MaxNum:'',
    MiniNum:'',
    Sprice:[],
  },
  mutations: {
    // 获取数据
    getCartList(state, data) {
      state.list = data.result
    },
    // 数量自增
    numJia(state, data) {
      data.num++;
    },
    // 数量自减
    numJian(state, data) {
      if (data.num == 1) {
        alert('你不买了吗？？？')
        return
      } else {
        data.num--
      }
    },
    //删除
    del(state, data) {
      state.list.splice(state.list.findIndex(item => item === data), 1)
    },
    // 选中全选
    checkAll(state) {
      let num = 0;
      state.list.forEach(item => {
        if (item.status) {
          num++
        }
      })
      if (num == state.list.length) {
        state.status = true;
      } else {
        state.status = false;
      }
    },
    // 全选
    allCheck(state) {
      
      state.status = !state.status
      console.log(state.status)
      if (state.status) {
        state.list.map(item => {
          item.status = true
        })
      }else{
        state.list.map(item => {
          item.status = false
        })
      }
    },
    // search
    search(state){
      let list = state.list.filter(item=>{
        if(state.MaxNum >item.price && state.MiniNum < item.price){
          return item
        }
      })
      state.list = list
    },
    getPX(state){
      
    },
    px(state){
      state.Sprice=[];
      state.list.forEach(item=>{
        state.Sprice.push(item.price)
      })
      // console.log(state.Sprice)
      state.Sprice.sort((a,b)=>{
        return a-b;
      })
      let list = [];
      state.Sprice.forEach(item=>{
        return state.list.filter(item1=>{
          if(item == item1.price){
              list.push(item1)
          }
        })
      })
      state.list = list
    },
    pxs(state){
      state.Sprice=[];
      state.list.forEach(item=>{
        state.Sprice.push(item.price)
      })
      // console.log(state.Sprice)
      state.Sprice.sort((a,b)=>{
        return b-a;
      })
      let list = [];
      state.Sprice.forEach(item=>{
        return state.list.filter(item1=>{
          if(item == item1.price){
              list.push(item1)
          }
        })
      })
      state.list = list
    }
  },
  actions: {
    // 请求数据
    async GetCartList(context) {
      const { data: res } = await axios.get('./list.json')
      // 调用 mutations
      context.commit('getCartList', res)
    }
  },
  modules: {
  },
  getters: {
    // 价格
    price(state) {
      let price = 0;
      state.list.forEach(item => {
        if (item.status) {
          price += item.price * item.num;
        }
      })
      return price
    }
  }
})
